using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using MySql.Data.MySqlClient;

namespace Base
{
	public static class DbProviderFactoryEx
	{
		public static DbProviderFactory GetFactory(string providerName)
		{
			if (providerName == null)
				throw new ArgumentNullException("providerName");

			switch (providerName)
			{
                case "MySql.Data.MySqlClient":
                    return new MySqlClientFactory();

				default:
					return DbProviderFactories.GetFactory(providerName);
			}
		}

		public static string GetParameterMarkerFormat(DbConnection connect)
		{
			if (connect == null)
				throw new ArgumentNullException("connect");

			Type type = connect.GetType();
            if (type == typeof(MySql.Data.MySqlClient.MySqlConnection))
                return MySqlParameterMarkerFormat;//mysql bug
            else
			if (type == typeof(System.Data.SqlClient.SqlConnection))
				return SqlServerParameterMarkerFormat;//ms bug

			connect.Open();
			string result = connect.GetSchema("DataSourceInformation").Rows[0]["ParameterMarkerFormat"].ToString();
			connect.Close();
			return result;
		}

		public static readonly string SqlServerParameterMarkerFormat = "@{0}";
		public static readonly string MySqlParameterMarkerFormat = "?{0}";
	}
	public static class DBHelper
	{
		public static T Get<T>(DbDataRecord record, string field)
		{
			int num = record.GetOrdinal(field);
			if (record.IsDBNull(num))
				return default(T);

			return (T)record[num];
		}

		public static int? ToInt32(object value)
		{
			if (value == null)
				return null;
			
			return ((IConvertible)value).ToInt32(null);
		}

		public static void AddParameter(string name, object value, DbCommand cmd)
		{
			DbParameter para = cmd.CreateParameter();
			para.ParameterName = string.Format(ParameterMarkerFormat, name);
			if (value == null)
				para.Value = DBNull.Value;
			else
			para.Value = value;
			cmd.Parameters.Add(para);
		}


        public static String LatinToGBK(String str)
        {
            try
            {
                byte[] bytesStr = Encoding.GetEncoding("latin1").GetBytes(str);
                return Encoding.GetEncoding("GB2312").GetString(bytesStr);
            }
            catch
            {
                return str;
            }
        }

        public static String GBKToLatin(String str)
        {
            try
            {
                byte[] bytesStr = Encoding.GetEncoding("GB2312").GetBytes(str);
                return Encoding.GetEncoding("latin1").GetString(bytesStr);
            }
            catch
            {
                return str;
            }
        } 
		public static string ParameterMarkerFormat = DbProviderFactoryEx.SqlServerParameterMarkerFormat;
	}
}
